<template>
	<detectingPanel v-if="loading"/>
	<BizDetectResultPanle :status="status" :key="statusKey"/>
	<div class="container">
		<div class="form-area">
			<a-form ref="formRef" :model="formData">
				<a-form-item label="鸡舍" name="henhouseId">
					<henhouseSelect ref="henhouseRef" @update:henhouseId="handleHenhouseIdUpdate"
									@update:henhouseName="handleHenhouseNameUpdate"/>
				</a-form-item>
				<a-form-item label="栏舍" name="barnId">
					<barnSelectByHenhouse ref="barnSelectRef" @update:barnId="handleBarnIdUpdate"
										  @update:barnName="handleBarnNameUpdate"/>
				</a-form-item>
				<a-form-item label="栏区" name="columnId">
					<columnSelectByBarn ref="columnSelectRef" @update:columnId="handleColumnIdUpdate"
										@update:columnName="handleColumnNameUpdate"/>
				</a-form-item>
			</a-form>

			<div class="detectedImageContainer" v-if="detectedImage">
				<img :src=" 'data:image/png;base64,' + detectedImage " alt="检测后图片" style="width: 300px; height: auto;">
			</div>
			<div class="uploadImage" v-if="uploadedImage">
				<img :src="uploadedImage" alt="上传图片" style="width: 300px; height: auto;">
			</div>
		</div>

		<div class="button-wrapper">
			<XnUpload ref="uploadRef" @uploadDone="uploadImgDone"/>
			<a-button type="primary" @click="sendMessage" style="width: 110px;margin-left: 50px">提交</a-button>
		</div>

	</div>

</template>

<script setup name="bizDetect">
	import bizDetectApi from "@/api/biz/bizDetectApi";
	import bizDetectRecordApi from "@/api/biz/bizDetectRecordApi";
	import {Form} from "ant-design-vue";
	import {cloneDeep} from "lodash-es";
	// import WebSocket from 'ws';
	import { useWebSocket } from 'vue-native-websocket';
	import tool from '@/utils/tool'

	// const socket = useWebSocket('ws://localhost:82/ws/detect?token=' + tool.data.get('TOKEN'))
	const socket = ref(null);
	const message = ref('');
	// 定义dom
	const uploadRef = ref();
	const uploadedImage = ref('');
	const detectedImage = ref('');
	// 检测状态
	let status = ref('');
	// resultPanel的key
	let statusKey = ref(0);
	const forceUpdate = ref(false);
	// 显示加载组件
	let loading = ref(false);
	//Dom 对象
	const formRef = ref();
	const barnSelectRef = ref();
	const columnSelectRef = ref();
	const formData = ref({
		henhouseId: -1,
		henhouseName:'',
		barnId: '',
		barnName:'',
		columnId: '',
		columnName:'',
	});
	const henhouseRef = ref();

	const connectWebSocket = () => {
		socket.value = new WebSocket('ws://127.0.0.1:82/ws/detect?token=' + tool.data.get('TOKEN'));
		//接收后端返回的结果
		socket.value.onmessage = (event) =>{
			if (event.data !== undefined){
				loading.value = false;
			}
			console.log(event.data);
			message.value = JSON.parse(event.data)
			status.value = message.value.result
			detectedImage.value = message.value.detectedImageBase64
			// 刷新结果面板
			update();
			// 清空回显图片
			uploadedImage.value = "";

			const emailData = {
				henhouseId: formData.value.henhouseId,
				barnId: formData.value.barnId,
				columnId: formData.value.columnId,
				result: status.value
			}
			//判断检测结果
			if (status.value === '异常'){
				console.log('发送异常')
				// 发送警告邮件
				bizDetectApi.sendWarningEmail(emailData)
					.then(() =>{
						console.log("sendEmail ");
					})
			}
		}
	};

	const closeWebSocket = () => {
		if (socket.value) {
			socket.value.close();
			socket.value = null;
		}
	};

	onActivated(() =>{
		connectWebSocket()
	})

	onDeactivated(() =>{
		closeWebSocket()
	})

	// 上传回调函数
	const uploadImgDone = (value) => {
		console.log(value)
		const file = value[0];
		uploadedImage.value = file.url;
		detectedImage.value = "";
	}

	/*
	* 因为这里不管结果是否与原来相同，都要重新渲染结果面板
	* 这里要手动刷新
	*/
	watch([status, forceUpdate], () => {
		statusKey.value += 1; // 改变key的值，触发重新渲染
		forceUpdate.value = false; // 重置forceUpdate的值
	});

	//向后端发送消息
	const sendMessage = () =>{
		const img_id = uploadedImage.value.match(/id=(\d+)/)[1];
		const raw_data = {
			imageId: img_id,
			henhouseId: formData.value.henhouseId,
			barnId: formData.value.barnId,
			columnId: formData.value.columnId,
		}
		const data = JSON.stringify(raw_data)
		//确保Websocket连接可用
		if (socket.value && socket.value.readyState === WebSocket.OPEN) {
			loading.value = true;
			socket.value.send(data);
		} else {
			console.log('WebSocket is not open');
		}
	}

	const update = () => {
		forceUpdate.value = true;
	}
	// 处理鸡舍id变化
	const handleHenhouseIdUpdate = (id) => {
		// 如果鸡舍id不为空则开启栏舍选择框并将id加入到formData中
		if (id !== undefined) {
			formData.value.henhouseId = id;
			barnSelectRef.value.selectByHenhouseId(id);
			barnSelectRef.value.barnDisable = false;
			detectedImage.value = undefined;
		}
		// 如果鸡舍id为空，则说明用户清空了鸡舍的选择框，这时我们要清空formData
		// 并且还要把栏舍选择框和栏区选择框禁用
		else {
			formData.value.henhouseId = undefined;
			formData.value.barnId = undefined;
			formData.value.columnId = undefined;
			barnSelectRef.value.barnDisable = true;
			barnSelectRef.value.barnId = undefined;
			columnSelectRef.value.columnDisable = true;
			columnSelectRef.value.columnId = undefined;
		}
	}

	const handleHenhouseNameUpdate = (name) => {
		formData.value.henhouseName = name;
	}
	// 处理栏舍id变化，逻辑与处理鸡舍id类似
	const handleBarnIdUpdate = (id) => {
		if (id !== undefined) {
			formData.value.barnId = id;
			columnSelectRef.value.selectByBarnId(id);
			columnSelectRef.value.columnDisable = false;
		} else {
			formData.value.barnId = undefined;
			formData.value.columnId = undefined;
			columnSelectRef.value.columnDisable = true;
			columnSelectRef.value.columnId = undefined;
		}
	}

	const handleBarnNameUpdate = (name) => {
		formData.value.barnName = name;
	}

	const handleColumnIdUpdate = (id) => {
		if (id !== undefined) {
			formData.value.columnId = id;
		} else {
			formData.value.columnId = undefined;
			columnSelectRef.value.columnId = undefined;
		}
	}

	const handleColumnNameUpdate = (name) => {
		formData.value.columnName = name;
	}
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.form-area {
	width: 50%;
	margin: auto;
}

.button-wrapper {
	margin-top: 20px;
}

.uploadImage{
	margin-top: 20px;
	text-align: center;
}

.detectedImageContainer{
	margin-top: 20px;
	text-align: center;
}
</style>
